﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using METU_CMT.Business;

namespace METU_CMT
{
    public class LocalEventDocument
    {
        private string teamName;
        private string documentName;
        private DateTime? uploadTime;
        private int deliverableId;
        private int teamId;
        private string description;
        private int eventId;
        private DateTime dueDate;
        private string submitterUserName;

        public string TeamName
        {
            get { return teamName; }
            set { teamName = value; }
        }

        public string DocumentName
        {
            get { return documentName; }
            set { documentName = value; }
        }

        public DateTime? UploadTime
        {
            get { return uploadTime; }
            set { uploadTime = value; }
        }

        public int DeliverableId
        {
            get { return deliverableId; }
            set { deliverableId = value; }
        }

        public int TeamId
        {
            get { return teamId; }
            set { teamId = value; }
        }

        public string Description
        {
            get { return description; }
            set { description = value; }
        }

        public int EventId
        {
            get { return eventId; }
            set { eventId = value; }
        }

        public DateTime DueDate
        {
            get { return dueDate; }
            set { dueDate = value; }
        }

        public string SubmitterUserName
        {
            get { return submitterUserName; }
            set { submitterUserName = value; }
        }
    }

    public partial class ListDownloadSubmittedDocsScreen : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindListOfSubmittedDocs();
            }
        }

        private void BindListOfSubmittedDocs()
        {
            Event _event = GetCurrentEvent();
            if (_event == null)
            {
                return;
            }
            CourseInstructor _currentCourse = (CourseInstructor)EntityFactory.GetCurrentCourse(UserType.Instructor);

            List<Deliverable> _works;
            List<Team> _teams;
            _currentCourse.GetTeamWork(_event, out _works, out _teams);

            SetDtgSubmittedDocumentsDatasource(_works, _teams);
        }

        private void SetDtgSubmittedDocumentsDatasource(List<Deliverable> works, List<Team> teams)
        {
            List<LocalEventDocument> _localEventDocuments = new List<LocalEventDocument>();
            for (int _i = 0; _i < teams.Count; _i++)
            {
                LocalEventDocument _localEventDocument = new LocalEventDocument();
                if (works[_i] != null)
                {
                    _localEventDocument.DeliverableId = works[_i].DeliverableId;
                    _localEventDocument.DocumentName = works[_i].File;
                    _localEventDocument.UploadTime = works[_i].UploadTime;
                }
                _localEventDocument.TeamName = teams[_i].TeamName;
                _localEventDocument.TeamId = teams[_i].TeamId;
                _localEventDocuments.Add(_localEventDocument);
            }
            dtgSubmittedDocuments.DataSource = _localEventDocuments;
            dtgSubmittedDocuments.DataBind();
        }

        private Event GetCurrentEvent()
        {
            if (Session["CurrentEvent"] != null)
            {
                return (Event)Session["CurrentEvent"];
            }
            return null;
        }

        protected void OnLnkBtnDownloadClicked(object sender, EventArgs e)
        {
            GridViewRow _gridViewRow = (GridViewRow)((LinkButton)sender).NamingContainer;
            int _teamId = CommonMethods.GetIdFromGridViewRow(_gridViewRow);

            Team _team = new Team(_teamId);
            _team.DownloadDeliverable(GetCurrentEvent());
        }

        protected void OnLnkBtnUploadClicked(object sender, EventArgs e)
        {
            GridViewRow _gridViewRow = (GridViewRow)((LinkButton)sender).NamingContainer;
            int _teamId = CommonMethods.GetIdFromGridViewRow(_gridViewRow);
            Team _team = new Team(_teamId);
            Event _event = GetCurrentEvent();
            ////TODO: Fill up the deliverable

            FileUpload _fileUpload = (FileUpload)_gridViewRow.FindControl("fuDocumentUpload");
            StringBuilder _dosyaAdi = new StringBuilder();
            DateTime _now = DateTime.Now;

            if (string.IsNullOrEmpty(_fileUpload.FileName))
            {
                //ShowAlert("Lütfen eklemek istediğiniz dosyayı seçiniz...");
                return;
            }
            HttpPostedFile _myFile = _fileUpload.PostedFile;
            string _fileExt = Path.GetExtension(_fileUpload.FileName);

            if (string.IsNullOrEmpty(_fileExt))
            {
                //ShowAlert("Yüklemek istediğiniz dosyanın uzantısı bulunamadı.");
                return;
            }

            if (_myFile.ContentLength > 10500000)
            {
                //ShowAlert("Yükleyeceğiniz dosyanın boyutu 10 MB sınırını geçmemelidir.");
                return;
            }
            if (!_fileExt.ToLower().Equals(".doc") && !_fileExt.ToLower().Equals(".docx") &&
                !_fileExt.ToLower().Equals(".txt") && !_fileExt.ToLower().Equals(".xls") &&
                !_fileExt.ToLower().Equals(".xlsx") && !_fileExt.ToLower().Equals(".pdf") &&
                !_fileExt.ToLower().Equals(".ppt") && !_fileExt.ToLower().Equals(".pptx") &&
                !_fileExt.ToLower().Equals(".jpg") && !_fileExt.ToLower().Equals(".bmp") &&
                !_fileExt.ToLower().Equals(".png") && !_fileExt.ToLower().Equals(".rtf") &&
                !_fileExt.ToLower().Equals(".jpeg"))
            {
                //ShowAlert(
                //    "Yalnızca Word, Excel, PowerPoint, PDF, Resim ve Video tipinde dosyalar yükleyebilirsiniz.");
                return;
            }
            if (_dosyaAdi.ToString().Contains("$"))
            {
                //TODO: Log: file name cannot contain $
                return;
            }

            _dosyaAdi.Append(
                Path.GetFileNameWithoutExtension(_fileUpload.FileName));
            _dosyaAdi.Append("$" + EntityFactory.User.UserId + "_");
            _dosyaAdi.Append(_now.ToString("yyyyMMddHHmmss"));
            StringBuilder _savePath =
                new StringBuilder(Server.MapPath("~/StudentDocuments/") + _dosyaAdi + _fileExt);

            _fileUpload.PostedFile.SaveAs(_savePath.ToString());

            _fileUpload.Dispose();

            Deliverable _deliverable = new Deliverable
                                           {
                                               Event = _event,
                                               DocType = _fileExt,
                                               File = _dosyaAdi + _fileExt,
                                               UploadTime = _now,
                                               RealFileName = _fileUpload.FileName
                                           };


            _team.UploadDeliverable(_deliverable, EntityFactory.User.UserId);
            string _toList = _team.Members.Aggregate(string.Empty, (current, student) => current + (student.Email + ";"));

            Course _currentCourse = EntityFactory.GetCurrentCourse(UserType.Student);
            _toList = _currentCourse.TAs.Aggregate(_toList,
                                                   (current, teachingAssistant) =>
                                                   current + (teachingAssistant.Email + ";"));

            Email _email = new Email("Submission behalf of your team",
                                     "The file descripted below is uploaded for your team by " + EntityFactory.User.Name +
                                     " " + EntityFactory.User.Surname + "<br/>Event Description: " + _deliverable.Event.Description
                                     + "<br/>Event Due Time: " + _deliverable.Event.DueDate.ToString("dd.MM.yyyy HH.mm")
                                     + "<br/>File Name: " + _deliverable.File
                                     + "<br/>Upload Time: " + _deliverable.UploadTime
                                     , _toList);
            
            _email.SendEmail();
            BindListOfSubmittedDocs();
        }

        protected void OnLnkBtnDownloadAllDocsClicked(object sender, EventArgs e)
        {
            CourseInstructor _currentCourse = (CourseInstructor)EntityFactory.GetCurrentCourse(UserType.Instructor);
            Event _event = GetCurrentEvent();
            _currentCourse.DownloadDocuments(_event);
        }

        protected void OnLnkBtnDownloadSubmissionReportsClicked(object sender, EventArgs e)
        {
            CourseInstructor _currentCourse = (CourseInstructor)EntityFactory.GetCurrentCourse(UserType.Instructor);
            Event _event = GetCurrentEvent();
            _currentCourse.DownloadSubmissionReport(_event);
        }

    }
}